//
//  BrowseImageScrollView.m
//  BigImageBrowse
//
//  Created by iOS开发 on 2018/8/15.
//  Copyright © 2018年 iOS开发. All rights reserved.
//

#import "BrowseImageScrollView.h"


@interface BrowseImageScrollView ()<UIScrollViewDelegate>
@property (nonatomic,strong) UITapGestureRecognizer *imageTap;
@end


@implementation BrowseImageScrollView

- (instancetype)initWithFrame:(CGRect)frame WithImage:(UIImage *)image
{
    self = [super initWithFrame:frame];
    if (self) {
        
        // 设置最大缩放比例
        self.maximumZoomScale = 3;
        // 设置最小缩放比例
        self.minimumZoomScale = 1;
        
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
        self.imageView.backgroundColor = [UIColor redColor];
        {
            
            _imageTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageView:)];
            [_imageTap setNumberOfTapsRequired:2];
            self.imageView.userInteractionEnabled = YES;
            [self.imageView addGestureRecognizer:_imageTap];
        }
        self.backgroundColor = [UIColor clearColor];
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        [self addSubview:_imageView];
        self.delegate = self;
        [self configurationImage:image];
        
    }
    return self;
}
//获取点击消失手势 处理手势冲突
- (void)setHiddtap:(UITapGestureRecognizer *)hiddtap{
    _hiddtap = hiddtap;
    [hiddtap requireGestureRecognizerToFail:_imageTap];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    // 延中心点缩放
    CGRect rect = _imageView.frame;
    rect.origin.x = 0;
    rect.origin.y = 0;
    if (rect.size.width < CGRectGetWidth(self.frame)) {
        rect.origin.x = floorf((CGRectGetWidth(self.frame) - rect.size.width) / 2.0);
    }
    if (rect.size.height < CGRectGetHeight(self.frame)) {
        rect.origin.y = floorf((CGRectGetHeight(self.frame) - rect.size.height) / 2.0);
    }
    _imageView.frame = rect;
}
- (void)configurationImage:(UIImage *)image{
    self.imageView.image = image;
    //计算imageView的frame
    CGFloat x = 0;
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = width / image.size.width * image.size.height;
    CGFloat y = 0;
    if(height < [UIScreen mainScreen].bounds.size.height){
        y = ([UIScreen mainScreen].bounds.size.height - height) * 0.5;
    }
    _imageView.frame = CGRectMake(x, y, width, height);

}

- (void)clickImageView:(UITapGestureRecognizer *)tap{
    if (self.zoomScale < 1) {
        [self setZoomScale:1 animated:YES];
    }else if (self.zoomScale == 1){
        [self setZoomScale:self.maximumZoomScale animated:YES];
    }else{
        [self setZoomScale:1 animated:YES];
    }

}

@end
